#ifdef __CBM__
#include <cbm.h>
#endif
#include <stdio.h>
#include "BbsControlData.h"
#include <errno.h>
#include <string.h>
#include <conio.h>
#include <unistd.h>
#include <device.h>

extern void _OVERLAY_START__;
extern void _OVERLAY_SIZE__;

#if defined(__C64__)
#define EXT ".c64"
#endif
#if defined(__C128__)
#define EXT ".c128"
#endif
#if defined(__APPLE2__)
#define EXT ".apple2"
#endif
#if defined(__ATARI__)
#define EXT ".atari"
#endif
#ifndef EXT
#define EXT ""
#endif

unsigned int loadOverlay(
	const char *overlayName, 
	void (*enterMethod)(void), 
	const char *returnToOverlay)
{
	char returnOverlay[17];
	int result;
	
	static FILE *file;
	static char oldDirectory[17];
	static char directory[17];
	static char filename[21];

	strcpy(returnOverlay, returnToOverlay);

	sprintf(filename, "%u:%s" EXT, bcd.bbsDirectory.drive, overlayName);

	getcwd(oldDirectory, 17);
	getdevicedir(bcd.bbsDirectory.device, directory, 17);
	chdir(directory);

	file = fopen(filename, "rb");

	if(file != NULL)
	{
		printf("\r\nfile: %s  start: %04X", filename, &_OVERLAY_START__);
#ifdef __CBM__
		result = fread(&_OVERLAY_START__, 2, 1, file);
		//printf("\r\nresult: %u  _oserror: %u", result, _oserror);
#endif
		result = fread(&_OVERLAY_START__, 1, (unsigned)&_OVERLAY_SIZE__, file);
		fclose(file);
		if(result != 0)
		{
			enterMethod();
		}
		else
		{
			printf("\r\n_oserror: %u", _oserror);
		}
	}
	else
	{
		printf("failed to load: %s", filename);
		return 0;
	}

	sprintf(filename, "%u:%s" EXT, bcd.bbsDirectory.drive, returnOverlay);

	getdevicedir(bcd.bbsDirectory.device, directory, 17);
	chdir(directory);

	file = fopen(filename, "rb");

	if(file != NULL)
	{
		printf("\r\nfile: %s  start: %04X\r\n", filename, &_OVERLAY_START__);
#ifdef __CBM__
		result = fread(&_OVERLAY_START__, 2, 1, file);
		//printf("\r\nresult: %u  _oserror: %u", result, _oserror);
#endif
		result = fread(&_OVERLAY_START__, 1, (unsigned)&_OVERLAY_SIZE__, file);
		fclose(file);
	}

	chdir(oldDirectory);

	return result;
}